class WxRequest {
  // 默认值
  defaults = {
    baseURL: "",
    url: "",
    data: null,
    method: "GET",
    header: {
      "Content-type": "application/json",
    },
    timeout: 60000,
  };

  //   定义拦截器对象
  interceptors = {
    request: (config) => config,
    response: (response) => response,
  };

  constructor(param = {}) {
    this.defaults = Object.assign({}, this.defaults, param);
  }

  request(options) {
    options.url = this.defaults.baseURL + options.url;
    options = { ...this.defaults, ...options };
    options = this.interceptors.request(options);

    return new Promise((resolve, reject) => {
      if (options.method === "UPLOAD") {
        wx.uploadFile({
          ...options,
          success: (res) => {
            res.data = JSON.parse(res.data);
            const mergeRes = Object.assign({}, res, {
              config: options,
              isSuccess: true,
            });
            resolve(this.interceptors.request(mergeRes));
          },
          fail: (err) => {
            const mergeErr = Object.assign({}, err, {
              config: options,
              isSuccess: false,
            });
            reject(this.interceptors.response(mergeErr));
          },
        });
      } else {
        wx.request({
          ...options,
          success: (res) => {
            const mergeRes = Object.assign({}, res, {
              config: options,
              isSuccess: true,
            });
            resolve(this.interceptors.request(mergeRes));
          },
          fail: (err) => {
            const mergeErr = Object.assign({}, err, {
              config: options,
              isSuccess: false,
            });
            reject(this.interceptors.response(mergeErr));
          },
        });
      }
    });
  }

  // 图书上传到服务器
  upload(url, filePath, name = "file", config = {}) {
    return this.request(
      Object.assign({ url, filePath, name, method: "UPLOAD" }, config)
    );
  }
}

export default WxRequest;
